package com.yilin.platform.base_core.tools.pab.utils;

import com.google.gson.reflect.TypeToken;
import com.yilin.platform.base_core.application.RedisClient;
import com.yilin.platform.base_core.commons.utils.JsonUtil;
import com.yilin.platform.base_core.commons.utils.StringUtil;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class PabTaskTools {

    private static String PLAT_BANK_PUB_SYNC_KEY = "PLAT_BANK_PUB_SYNC_KEY";

    private static String SINGLE_FILED = "singleTrade";
    private static String BATCH_FILED = "batchTrade";

    /**
     * 添加支付任务
     */
    public void addTradeNoTask(String tradeNo) {
        addTask(tradeNo,SINGLE_FILED);
    }

    /**
     * 添加支付任务
     */
    public void addBatchNoTask(String batchNo) {
        addTask(batchNo,BATCH_FILED);
    }

    private void addTask(String no, String filed) {
        String dataJson = RedisClient.getInstance().hget(PLAT_BANK_PUB_SYNC_KEY, filed);
        if (dataJson == null) dataJson = "[]";
        List<String> batchOrSingleNoList = JsonUtil.jsonToObject(dataJson, new TypeToken<List<String>>() {});
        batchOrSingleNoList.add(no);
        String toJson = JsonUtil.objectToJson(batchOrSingleNoList);
        RedisClient.getInstance().hset(PLAT_BANK_PUB_SYNC_KEY, filed, toJson);
    }

    /**
     * 获取处理任务
     */
    public List<String> getTradeNoList() {
        return getTask(SINGLE_FILED);
    }

    /**
     * 获取处理任务
     */
    public List<String> getBatchNoList() {
        return getTask(BATCH_FILED);
    }

    private List<String> getTask(String filed) {
        String dataJson = RedisClient.getInstance().hget(PLAT_BANK_PUB_SYNC_KEY, filed);
        if (dataJson == null) dataJson = "[]";
        return JsonUtil.jsonToObject(dataJson, new TypeToken<List<String>>() {});
    }

    /**
     * 移除任务
     * */
    public void removeTradeNo(String tradeNo) {
        removeTask(tradeNo, SINGLE_FILED);
    }

    /**
     * 移除任务
     */
    public void removeBatchNo(String tradeNo) {
        removeTask(tradeNo, BATCH_FILED);
    }

    private void removeTask(String no,String filed) {
        String dataJson = RedisClient.getInstance().hget(PLAT_BANK_PUB_SYNC_KEY, filed);
        if (StringUtil.isEmpty(dataJson)) dataJson = "[]";
        List<String> stringList = JsonUtil.jsonToObject(dataJson, new TypeToken<List<String>>() {});
        stringList.remove(no);
        String toJson = JsonUtil.objectToJson(stringList);
        RedisClient.getInstance().hset(PLAT_BANK_PUB_SYNC_KEY, filed, toJson);
    }



}
